//
//  UserRegisterNameVC.m
//  danpin
//
//  Created by chuangjia on 30/6/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "UserRegisterNameVC.h"
#import "ZToastManager.h"
#import "BaseModel.h"
#import "BaseCell.h"
@interface UserRegisterNameVC ()<UITextFieldDelegate,UIAlertViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,strong) UITextField     *txtNickname;
@property(nonatomic,strong) UIImageView  *iconView;
@property(nonatomic,strong) UIImageView  *iconDefaultView;
@property(nonatomic,strong) UILabel  *logLabel;
@property(nonatomic,strong) UIImage  *iconImage;
@property (weak) id<UserDelegate> delegate;
+ (instancetype)newController;

@end

@implementation UserRegisterNameVC
+ (instancetype)newController
{
    return [super new];
}

+ (instancetype)newWithDelegate:(id<UserDelegate>)delegate
{
    UserRegisterNameVC *viewController = [UserRegisterNameVC newController];
    
    if (viewController) {
        viewController.delegate = delegate;
    }
    
    return viewController;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.rightTitle =@"完成";
    self.navTitle =@"设置昵称";
    self.view.backgroundColor = [UIColor whiteColor];
    [self initUI];
    UITapGestureRecognizer* singleRecognizer= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFrom)];
    self.view.userInteractionEnabled =YES;
    [self.view addGestureRecognizer:singleRecognizer];
    singleRecognizer=nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
      DLog(@"%s", __PRETTY_FUNCTION__);
}

-(void)clickNavEvent:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0:
        {
            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        case 1:
        {
            [self okAction];
        }
            break;
        default:
            break;
    }
}
-(void)okAction
{
    [self btnLoginAction];
}
-(UIImageView*)iconView
{
    if (!_iconView) {
        UITapGestureRecognizer* singleRecognizer= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFromIcon)];
        self.iconView =[[UIImageView alloc] initWithFrame:CGRectZero];
        self.iconView.frame = CGRectMake((DEVICE_WIDTH-80)/2,35, 80, 80);
        self.iconView.layer.cornerRadius=40;
        self.iconView.layer.masksToBounds = YES;
        self.iconView.image =[UIImage imageNamed:@"user_face.png"];
        self.iconView.userInteractionEnabled =YES;
        [self.iconView addGestureRecognizer:singleRecognizer];
        [self.view addSubview:self.iconView];
        singleRecognizer=nil;
    }
    
    return _iconView;
}
-(UIImageView*)iconDefaultView
{
    if (!_iconDefaultView) {
        UITapGestureRecognizer* singleRecognizer= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFromIcon)];
        self.iconDefaultView =[[UIImageView alloc] initWithFrame:CGRectZero];
        self.iconDefaultView.frame = CGRectMake((DEVICE_WIDTH-80-32)/2,35, 32, 32);
        self.iconDefaultView.image =[UIImage imageNamed:@"add_userface.png"];
        self.iconDefaultView.userInteractionEnabled =YES;
        [self.iconDefaultView addGestureRecognizer:singleRecognizer];
        [self.view addSubview:self.iconDefaultView];
        singleRecognizer=nil;
    }
    
    return _iconDefaultView;
}
-(UILabel*)logLabel
{
    if (!_logLabel) {
        self.logLabel =[[UILabel alloc] initWithFrame:CGRectZero];
        self.logLabel.backgroundColor =[UIColor clearColor];
        self.logLabel.font = FONT(12);
        self.logLabel.textColor =UIColorFromRGB(0xcccccc);
        self.logLabel.textAlignment = NSTextAlignmentCenter;
        self.logLabel.text =@"单品 - 以一顶百";
        [self.view addSubview:self.logLabel];
    }
    return _logLabel;
}

-(UITextField *)txtNickname
{
    if (!_txtNickname) {
        self.txtNickname = [[UITextField alloc] initWithFrame:CGRectZero];
        self.txtNickname.placeholder = @"你叫什么名字";
        [self.txtNickname setBorderStyle:UITextBorderStyleRoundedRect];
        self.txtNickname.font = FONT(13);
        self.txtNickname.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_email"];
        self.txtNickname.autocorrectionType = UITextAutocorrectionTypeNo;
        self.txtNickname.autocapitalizationType = UITextAutocapitalizationTypeNone;
        self.txtNickname.returnKeyType = UIReturnKeyGo;
        self.txtNickname.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.txtNickname.delegate=self;
        [self.view addSubview:self.txtNickname];
    }
    return _txtNickname;
}
-(void)handleSingleTapFrom
{
    [self.txtNickname resignFirstResponder];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    [self btnLoginAction];
    return YES;
}
-(void)initUI
{
    self.iconView.frame = CGRectMake((DEVICE_WIDTH-80)/2,80, 80, 80);
    self.iconDefaultView.frame = CGRectMake((DEVICE_WIDTH-80)/2+60,130, 32, 32);
    self.txtNickname.frame =CGRectMake(PHOTO_FRAME_WIDTH*2, 200, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*4, PHOTO_FRAME_WIDTH*4);
}
//
- (void)btnLoginAction
{
    if(self.txtNickname.text.length==0)
    {
        [[ZToastManager ShardInstance] showtoast:@"请输入你的名字!"];
        return;
    }
    if (self.iconImage==nil) {
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您没有设置头像，是否现在设置?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
        return;
    }
    [self upLoadIcon:self.iconImage name:self.txtNickname.text];
}
-(void)handleSingleTapFromIcon
{
    [self.txtNickname resignFirstResponder];
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"相册选择",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *nickname =self.txtNickname.text;
    [self.txtNickname resignFirstResponder];
    switch (buttonIndex) {
        case 0:
        {
            [self upLoadIcon:nil name:nickname];
        }
            break;
        case 1:
        {
            UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                          initWithTitle:nil
                                          delegate:self
                                          cancelButtonTitle:@"取消"
                                          destructiveButtonTitle:nil
                                          otherButtonTitles:@"拍照", @"相册选择",nil];
            actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
            [actionSheet showInView:self.view];
        }
            break;
            
        default:
            break;
    }
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:  //打开照相机拍照
            [self takePhoto];
            break;
        case 1:  //打开本地相册
            [self LocalPhoto];
            break;
    }
}
//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        DLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
    
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* imageo = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *image = [self scaleImage:imageo toScale:0.3];
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        //图片保存的路径
        self.iconView.image = image;
        self.iconImage = image;
       
    }
}
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    DLog(@"您取消了选择图片");
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)upLoadIcon:(UIImage *)image name:(NSString *)name
{
    [BaseModel userinfo:name image:image success:^(AFHTTPRequestOperation *operation, id resultObject) {
        DLog(@"%@",resultObject);
        
        [[ZToastManager ShardInstance] showtoast:[resultObject objectForKey:@"msg"]];
        if ([[resultObject objectForKey:@"code"] intValue]==1)
        {
            [[ZShare sharedInstance] initUserInfo:resultObject];
            if (_delegate&&[_delegate respondsToSelector:@selector(userLoginOK:)]) {
                [_delegate userLoginOK:[ZShare sharedInstance].userInfo];
            }
        }
        
        
    } failure:^(NSError *error) {
        DLog(@"您取消了选择图片---%@",error);
        if (_delegate&&[_delegate respondsToSelector:@selector(userLoginFail)]) {
            [_delegate userLoginFail];
        }
    }];
}

@end
